import Vue from 'vue'
import store from '../'
import Cmd from '../../config/Cmd'


import {actions_const} from "../../config/StoreConstant";
import {macStringfy} from "../../utils/MessageHandler";
const state = {
    isConnected: false,
    message: '',
    reconnectError: false
}
const mutations = {
  SOCKET_ONOPEN (state, event)  {
    // console.log(store)
    Vue.prototype.$socket = event.currentTarget
    state.isConnected = true

  },
  SOCKET_ONCLOSE (state, event)  {
    state.isConnected = false
  },
  SOCKET_ONERROR (state, event)  {
    console.error(state, event)
  },
  // default handler called for all methods
  SOCKET_ONMESSAGE (state, message)  {
    state.message = message
    switch (message.cmd){
      case Cmd.WRITE:
        console.log(message);
        vueMain.$store.dispatch(actions_const.GET_CLASS_MEMBER).then( () => {

          vueMain.$store.getters.getMemberByMac(macStringfy(message.para['pen-mac-addr']))
        })
        break;
      case Cmd.NOTIFY:
        console.log(message);break;
      case Cmd.ON_LINE_STATE:
        console.log(message);break;
      case Cmd.CHECK_ON_LINE_SINGLE:
        console.log(message);break;
      case Cmd.ADD_DEVICE:
        console.log(message);break;
      case Cmd.SET_TIME:
        console.log(message);break;
      case Cmd.SET_WRITE_STATE:
        console.log(message);break;
      case Cmd.SET_DEVICE_OFFLINE:
        console.log(message);break;
      case Cmd.CALL_BACK:
        console.log(message);break;
    }
  },
  // mutations for reconnect methods
  SOCKET_RECONNECT(state, count) {
    console.info(state, count)
  },
  SOCKET_RECONNECT_ERROR(state) {
    state.reconnectError = true;
  },
}
const actions = {
  sendMessage: function(context, message) {

    Vue.prototype.$socket.sendObj(message)
  }
}

const getters = {
  connectionState(){
    return state.isConnected
  }
}

export default {
  state,
  actions,
  mutations
}
